package cz.jm.web.jmlib.client.dialog.validation.validators;

import cz.jm.web.jmlib.client.dialog.validation.HasValidationValue;
import cz.jm.web.jmlib.client.dialog.validation.Validator;

/** Validator kontrolujuci validitu podla regularneho vyrazu.
 * Vhodne je dosadit presnejsiu (lokalizovanu) chybovu hlasku
 * pomocou {@linkplain RegexpValidator#setValidationFailMessage(String)}.*/
public class RegexpValidator implements Validator {
	private String failMessage = "";
	private HasValidationValue valueHolder;
	private String pattern = "";
	
	public RegexpValidator(String pattern, HasValidationValue valueHolder) {
		setPattern(pattern);
		this.valueHolder = valueHolder;
	}
	
	public RegexpValidator(String pattern, HasValidationValue valueHolder, String failMessage) {
		setPattern(pattern);
		this.valueHolder = valueHolder;
		this.failMessage = failMessage;
	}
	
	@Override
    public boolean validate() {
		String value = valueHolder.getValidationValue();		
	    boolean isValid = value.matches(pattern);
	    return isValid;
    }

	public void setPattern(String pattern) {
		this.pattern = pattern;
    }

	
	public void setValidationFailMessage(String failMessage) {
		this.failMessage = failMessage;
	}
	
	public String getValidationFailMessage() {
		if (failMessage.isEmpty()) {
			return constants.valueNoMatchRegexpPattern() + " " + pattern;
		}
		else {
			return failMessage;
		}
	}

	protected HasValidationValue getValueHolder() {
    	return valueHolder;
    }

	public void setValueHolder(HasValidationValue valueHolder) {
    	this.valueHolder = valueHolder;
    }
}
